package com.sanhuo.security.filter;

import com.sanhuo.lib.ExceptionUtil;
import com.sanhuo.security.RoleVO;
import com.sanhuo.security.UserVo;
import com.sanhuo.security.entity.User;
import com.sanhuo.security.entity.UserToken;
import com.sanhuo.security.service.RoleService;
import com.sanhuo.security.service.UserService;
import com.sanhuo.security.service.UserTokenService;
import com.sanhuo.security.uitls.UserHolder;
import com.sanhuo.security.uitls.VerifyCodeHolder;
import com.sanhuo.utils.basic.BeanUtil;
import com.sanhuo.utils.basic.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.sanhuo.security.contains.State.SYSTEM_WRONG;

/**
 * 登录拦截器
 */
@Component(value = "loginFilter")
@CrossOrigin
public class LoginFilter extends HandlerInterceptorAdapter {

    private final String USERNAME = "id";
    private final String PASSWORD = "password";
    private final String VRCORD = "verifyCode";
    private final String SESSIONVRCODE = "session_vrCode";
    private final String USER = "author";


    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private UserTokenService userTokenService;

    @Override
    @CrossOrigin
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IllegalAccessException, IOException {
        //从请求的请求体中获取属性名为"userName"的值
        String username = obtainUsername(request);
        //从请求的请求体中获取属性名为"password"的值
        String password = obtainPassword(request);
        //从请求的请求体中获取属性名为"vrCode"的值
        String user_vrcode = obtainVrcode(request);
        //从内存中获取该ip最后一次请求的验证码的文本
        String session_vrCode = obtainSessionVrcode(request);
        //通过username从数据库中找到对应的用户信息对象
        User user = userService.findById(username);
        /* 验证 */
        ExceptionUtil.throwException(BeanUtil.isNull(user), SYSTEM_WRONG, "用户账号不存在!");
        ExceptionUtil.throwException(!user.getPassword().equals(password), SYSTEM_WRONG, "密码错误!");
        ExceptionUtil.throwException(!session_vrCode.equalsIgnoreCase(user_vrcode), SYSTEM_WRONG, "验证码错误!");
        ExceptionUtil.throwException(StringUtil.isBlank(username), "未通过登录验证,请登陆");
        /* */
        UserVo userVo = new UserVo();
        BeanUtil.copyBean(user, userVo);
        if (StringUtil.isNotBlank(user.getRoleId())) {
            RoleVO role = roleService.detail(user.getRoleId());
            if (BeanUtil.isNotNull(role)) {
                userVo.setRole(role);
            }
        }
        /* 更新token */
        UserToken userToken = userTokenService.updateToken(user.getId());
        userVo.setToken(userToken.getTokenStr());
        /* 保存用户信息到map*/
        UserHolder.put(userToken.getTokenStr(), userVo);
        request.setAttribute("token", userToken.getTokenStr());
        return true;
    }

    private String obtainUsername(HttpServletRequest request) {
        return request.getParameter(USERNAME);
    }

    private String obtainPassword(HttpServletRequest request) {
        return request.getParameter(PASSWORD);
    }

    private String obtainVrcode(HttpServletRequest request) {
        return request.getParameter(VRCORD);
    }

    private String obtainSessionVrcode(HttpServletRequest request) throws IOException {
        String result = VerifyCodeHolder.get(request);
        return result;
    }
}
